import { Form, Input } from 'antd';
import { forwardRef, useEffect, useImperativeHandle } from 'react';
import { IFolderFormProps, TFolderRef } from './interface';

const rules = (text: string) => {
  return [{ required: true, message: `请输入${text}` }];
};

const AddOrEditFolderForm = forwardRef<TFolderRef, IFolderFormProps>((props, ref) => {
  const [form] = Form.useForm();
  const { type, resourceId, resourceName } = props;
  const onSubmit = () => {
    return form
      .validateFields()
      .then((val) => {
        const finalValues = { ...val, type };
        if (type === 'edit') {
          finalValues.resourceId = resourceId;
        }
        return Promise.resolve(finalValues);
      })
      .catch((err) => {
        // message.error(' AddOrEditFolderForm ERR ');
        return Promise.reject(err);
      });
  };

  useEffect(() => {
    if (type === 'edit' && resourceId) {
      form.setFieldsValue({ resourceName });
    }
  }, [type]);

  useImperativeHandle(ref, () => ({
    onSubmit,
  }));

  return (
    <div style={{ padding: '16px 16px 0' }}>
      <Form layout="horizontal" form={form}>
        <Form.Item name="resourceName" label="名称" rules={rules('文件夹名称')}>
          <Input maxLength={20} placeholder="请输入" />
        </Form.Item>
      </Form>
    </div>
  );
});

export default AddOrEditFolderForm;
